package org.anarcoding.twitterbot.view;

import org.anarcoding.twitterbot.model.AnarcoTwitterBotConf;
import org.anarcoding.twitterbot.model.AnarcoTwitterException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import com.anarcoding.util.SWTUtil;

public class ShlAnarcoTwitterBotConfControl {

	private CmpAnarcoTwitterBotConf	compo;

	public ShlAnarcoTwitterBotConfControl( CmpAnarcoTwitterBotConf comp ) {

		compo = comp;

		compo.getBtnAdherir().addSelectionListener( new SelectionAdapter() {
			public void widgetSelected( SelectionEvent e ) {
				try {
					eventoAdherir();
				} catch( AnarcoTwitterException e1 ) {
					SWTUtil.openDialog( compo.getShell(), "Error", "" + e1.getMessage(), SWT.ICON_ERROR );
					e1.printStackTrace();
				}
			}
		} );

		KeyAdapter keyAd = new KeyAdapter() {
			public void keyPressed( KeyEvent e ) {
				if( e.keyCode == 13 )
					try {
						eventoAdherir();
					} catch( AnarcoTwitterException e1 ) {
						SWTUtil.openDialog( compo.getShell(), "Error", "" + e1.getMessage(), SWT.ICON_ERROR );
						e1.printStackTrace();
					}
			}
		};

		compo.getTxtConsumerKey().addKeyListener( keyAd );
		compo.getTxtConsumerSecret().addKeyListener( keyAd );
		compo.getTxtTwitterToken().addKeyListener( keyAd );
		compo.getTxtTwitterTokenSecret().addKeyListener( keyAd );

	}

	private void eventoAdherir() throws AnarcoTwitterException {
		String consumerKey, consumerSecret, twitterToken, twitterTokenSecret;

		consumerKey = compo.getTxtConsumerKey().getText().trim();
		consumerSecret = compo.getTxtConsumerSecret().getText().trim();
		twitterToken = compo.getTxtTwitterToken().getText().trim();
		twitterTokenSecret = compo.getTxtTwitterTokenSecret().getText().trim();

		if( consumerKey.isEmpty() || consumerSecret.isEmpty() || twitterToken.isEmpty() || twitterTokenSecret.isEmpty() )
			throw new AnarcoTwitterException( "Todos los campos son necesarios." );

		AnarcoTwitterBotConf nuevaConf = new AnarcoTwitterBotConf();
		nuevaConf.setConsumerKey( consumerKey );
		nuevaConf.setConsumerSecret( consumerSecret );
		nuevaConf.setTwitterToken( twitterToken );
		nuevaConf.setTwitterTokenSecret( twitterTokenSecret );

		compo.setNuevaConf( nuevaConf );

		compo.getShell().close();
	}

	public void actualizaCampos() {
		AnarcoTwitterBotConf conf = compo.getNuevaConf();

		compo.getTxtConsumerKey().setText( conf.getConsumerKey() );
		compo.getTxtConsumerSecret().setText( conf.getConsumerSecret() );
		compo.getTxtTwitterToken().setText( conf.getTwitterToken() );
		compo.getTxtTwitterTokenSecret().setText( conf.getTwitterTokenSecret() );
	}

}
